package com.yt.server.io.amf3;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.ASObject;
import flex.messaging.io.amf.Amf3Output;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import com.yt.server.messaging.Packet;

/**
 * AMF3编码器
 * 
 * @author LiuJ
 */
public class AMF3Encoder extends ProtocolEncoderAdapter {

	private static int cachesize = 1024;

	private final AttributeKey DEFLATER = new AttributeKey(getClass(),
			"deflater");

	private final AttributeKey AMF3OUTPUTKEY = new AttributeKey(getClass(),
			"Amf3Output");

	private final SerializationContext context = new SerializationContext();

	public AMF3Encoder() {
	}

	@Override
	public void dispose(IoSession session) throws Exception {
		Amf3Output amf3Output = (Amf3Output) session
				.getAttribute(AMF3OUTPUTKEY);
		session.removeAttribute(AMF3OUTPUTKEY);
		amf3Output.close();
	}

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		IoBuffer buffer = null;
		Amf3Output amf3Output = null;
		ByteArrayOutputStream outputStream = null;
		String sid = String.valueOf(session.getId());
		try {
			if (message instanceof String) {
				byte[] bytes = ((String) message).getBytes("UTF-8");
				buffer = IoBuffer.allocate(bytes.length + 1);
				buffer.put(bytes);
				buffer.put((byte) 0x0);
				buffer.flip();
				out.write(buffer);
				buffer.free();
			} else if (message != null
					&& (message instanceof ASObject || message instanceof Packet)) {
				Object output = session.getAttribute(AMF3OUTPUTKEY);
				if (output != null) {
					amf3Output = (Amf3Output) output;
				} else {
					amf3Output = new Amf3Output(context);
					session.setAttribute(AMF3OUTPUTKEY, amf3Output);
				}
				outputStream = new ByteArrayOutputStream();
				amf3Output.setOutputStream(outputStream);
				amf3Output.writeObject(message);
				amf3Output.flush();
				byte compressBytes[] = compress(session,
						outputStream.toByteArray());
				buffer = IoBuffer.allocate(compressBytes.length + 4, false)
						.setAutoExpand(true);
				buffer.putInt(compressBytes.length);
				buffer.put(compressBytes);
				buffer.flip();
				if (buffer != null) {
					out.write(buffer);
					out.flush();
				}
			}
		} catch (Exception e) {
			System.out.println(sid + " : AMF3Encoder Exception " + e);
			e.printStackTrace();
		} finally {
			if (null != amf3Output)
				amf3Output.reset();
			if (null != outputStream)
				outputStream.close();
			if (null != buffer)
				buffer.free();
		}
	}

	private byte[] compress(IoSession session, byte[] inputs) {
		Deflater deflater = (Deflater) session.getAttribute(DEFLATER);
		if (deflater == null) {
			deflater = new Deflater();
			session.setAttribute(DEFLATER, deflater);
		}
		deflater.reset();
		deflater.setInput(inputs);
		deflater.finish();
		byte outputs[] = new byte[0];
		ByteArrayOutputStream stream = new ByteArrayOutputStream(inputs.length);
		byte[] bytes = new byte[cachesize];
		int value;
		while (!deflater.finished()) {
			value = deflater.deflate(bytes);
			stream.write(bytes, 0, value);
		}
		outputs = stream.toByteArray();
		try {
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outputs;
	}
}